#import "RNLayoutView.h"
#import "RNLayoutHelper.h"

NSString * const RNLayoutViewLayoutHelperKey = @"layoutHelper";

@implementation RNLayoutView

@synthesize layoutHelper = layoutHelper_;

-(id)initWithFrame:(NSRect)theFrame {
    if (!(self = [super initWithFrame:theFrame]))
        return nil;
    [self setLayoutHelper:[[RNLayoutHelper alloc] initWithView:self]];
    [self setAutoresizesSubviews:NO];
    [self setAutoresizingMask:NSViewNotSizable];

    return self;
}

-(void)encodeWithCoder:(NSCoder *)theCoder {
    [super encodeWithCoder:theCoder];
    
    [theCoder encodeObject:[self layoutHelper] forKey:RNLayoutViewLayoutHelperKey];
}

-(id)initWithCoder:(NSCoder *)theCoder {
    if (!(self = [super initWithCoder:theCoder]))
        return nil;
    [self setLayoutHelper:[theCoder decodeObjectForKey:RNLayoutViewLayoutHelperKey]];
    [self setAutoresizesSubviews:NO];
    [self setAutoresizingMask:NSViewNotSizable];
    return self;
}

-(void)setFrameSize:(NSSize)aSize {
    [super setFrameSize:aSize];
    [[self layoutHelper] tile];
}

-(NSView<RNLayoutView> *)parent {
    if ([[self superview] conformsToProtocol:@protocol(RNLayoutView)])
        return (NSView<RNLayoutView> *)[self superview];
    return nil;
}

-(NSArray *)children {
    NSMutableArray *children = [NSMutableArray array];
    for (NSView *childView in [self subviews]) {
        if ([childView conformsToProtocol:@protocol(RNLayoutView)])
            [children addObject:childView];
    }
    return ([children count] == 0 ? nil : children);
}

@end
